import react, { useEffect,useState } from 'react'
import './index.css'
const LinkBacktop:react.FC<LinkBacktop> = (props:LinkBacktop) => {
  const [state,setState] = useState({
    children: props.children ? props.children : '顶部',
    color: props.color ? props.color : '#fff',
    fontSize: props.fontSize ? props.fontSize : '16px',
    backgroundColor: props.backgroundColor ? props.backgroundColor : '#000',
    borderColor: props.borderColor ? props.borderColor : 'transparent',
    isShow:false,
    clientWidth:0
  })
  const scrollY= props.scrollY ? props.scrollY : 0
  useEffect(()=>{
    scroolTop()
    scroll();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[state.clientWidth])
   // 返回顶部方法
  const  blackTop = () => {
    let timer = setInterval(() => {
      window.scroll(0, window.scrollY - 50);
      if (window.scrollY === 0) {
        clearInterval(timer)
      }
    }, 15);
  }
  // 监听滚轮
 const scroll = () => {
    window.addEventListener('scroll', scroolTop);
  }
  // 设置后显示按钮
  const scroolTop=()=> {
    let top = document.querySelector('.tops')
    
    const clientWidth = top?.clientWidth
    // const { scrollY: scroll } = state
    // let scrollY = scroll as number
    
    if (window.scrollY >= scrollY) {
      setState(state=>{
        state.isShow = true
        return {...state}
      })
    } else {
      setState(state=>{
        state.isShow = false
        state.clientWidth = clientWidth as number
        return {...state}
      })
    }

  }
  const { isShow, children, clientWidth, color, fontSize, backgroundColor, borderColor } = state
  
  return (
    <div className='tops' onClick={blackTop} style={{
      right: isShow ? '30px' : '-' + (clientWidth as number + 30) + 'px',
      color,
      fontSize,
      backgroundColor,
      borderColor,
      opacity:isShow?'1':'0',
    }}>
      {children}
    </div>
  )
}
export default LinkBacktop